package com.xiaoyg.algorithm;

import lombok.Data;

import java.util.List;

/**
 * 翻转链表
 */
@Data
public class ReverseList {

    static class ListNode{
        int val;
        ListNode next;

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }

        public ListNode(int val, ListNode next){
            this.val = val;
            this.next = next;
        }

    }


    public static ListNode reverse(ListNode head){
        ListNode pre = null,next;
        //当前节点为头结点
        ListNode curr = head;
        //循环终止条件是当前节点指向空
        while (curr!=null){
            //下一个节点是当前节点的next
            next = curr.next;
            //断链，直向前一个节点
            curr.next = pre;
            pre = curr;
            curr = next;

        }
        return pre;
    }

    /***
     * 递归
     * @param head
     * @return
     */
    public static ListNode recursion(ListNode head){
        //递归退出条件，空链表，或者只有一个元素，不需要翻转
        if (head == null || head.next == null){
            //5
            return head;
        }
        //变量保存返回值
        //5,5->4,5->4->3,5->4->3->2,5->4->3->2->1
        ListNode newHead = recursion(head.next);
        //1-2-3-4-5, 让5->4翻转
        //4->5->null = 4;3->4->null=3;2->3->null=2;1->2->null=1
        head.next.next = head;
        //4(->)5->4->..;3(->)4->3->..;2(->)3->2->..;1(->)2->1->..
        //防止形成环，断链，将head.next = null
        //4->null;3->null;2->null;1->null
        head.next = null;
        //每层递归返回没有被翻转的最后一个节点
        //5->null;5->4->null;5->4->3->null;5->4->3->2->null;5->4->3->2->1->null
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        System.out.println(node1);
//        ListNode iterate = iterate(node1);
        ListNode recursion = recursion(node1);
        System.out.println(recursion);
    }

}
